import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/model/shop/tbcate_model.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yres/pages/shop/tb_list_page.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import '../../pages/shop/SearchGoods.dart';

class TBCategoryPage extends StatefulWidget {
  TBCategoryPage({Key key}) : super(key: key);

  _TBCategoryPageState createState() => _TBCategoryPageState();
}

class _TBCategoryPageState extends State<TBCategoryPage> {
  EasyRefreshController _controller = new EasyRefreshController();
  int _selectIndex = 0;
  List _leftCateList = [];
  List _rightCateList = [];
  @override
  void initState() {
    super.initState();
    _getLeftCateData();
  }

  //左侧数据：
  _getLeftCateData() async {
    FormData data = new FormData.fromMap({});
    Response<String> response =
        await HttpUtil().post(Api.GetTBTopCatListUrl, data: data);
    Map userMap = json.decode(response.data);
    CateModelEntity itemEntity = new CateModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          _leftCateList.clear();
          _leftCateList = itemEntity.data;
          _getRightCateData(_leftCateList[0].taobao_cat_id);
        });
      }
    }
  }

  //右侧数据：
  _getRightCateData(pid) async {
    FormData data = new FormData.fromMap({'pid': pid});
    Response<String> response =
        await HttpUtil().post(Api.GetTBSubListByParentUrl, data: data);
    Map userMap = json.decode(response.data);
    // print(userMap);
    CateModelEntity itemEntity = new CateModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          _rightCateList.clear();
          _rightCateList = itemEntity.data;
        });
      }
    }
  }

  //左侧组件
  Widget _leftCateWidget(leftWidth) {
    if (_leftCateList.length > 0) {
      return Container(
        width: leftWidth,
        height: double.infinity,
        // color: Colors.red,
        child: ListView.builder(
          itemCount: _leftCateList.length,
          itemBuilder: (context, index) {
            return Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    setState(() {
                      // setState(() {
                      _selectIndex = index;
                      this._getRightCateData(
                          this._leftCateList[index].taobao_cat_id);
                    });
                    // print(_selectIndex);
                  },
                  child: Container(
                    width: double.infinity,
                    height: ScreenUtil.getInstance().setHeight(80),
                    padding: EdgeInsets.all(ScreenUtil.getInstance().setWidth(20)),
                    child: Text(
                      "${_leftCateList[index].name}",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE)),
                    ),
                    color: _selectIndex == index
                        ? Color.fromRGBO(240, 246, 246, 0.9)
                        : Colors.white,
                  ),
                ),
                Divider(height: 1),
              ],
            );
          },
        ),
      );
    } else {
      return Container(
        width: leftWidth,
        height: double.infinity,
      );
    }
  }

  //右侧组件：
  Widget _rightCateWidget(rightItemWidth, rightItemHeigth) {
    if (this._rightCateList.length > 0) {
      return Expanded(
        flex: 1,
        child: Container(
          padding: EdgeInsets.all(10),
          height: double.infinity,
          color: Color.fromRGBO(240, 246, 246, 0.9),
          // color: Colors.blue,
          child: GridView.builder(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                childAspectRatio: rightItemWidth / rightItemHeigth,
                crossAxisSpacing: ScreenUtil.getInstance().setWidth(20) * 4,
                mainAxisSpacing: ScreenUtil.getInstance().setWidth(20) * 2.8),
            itemCount: this._rightCateList.length,
            itemBuilder: (context, index) {
              return Container(
                // padding: EdgeInsets.all(ScreenAdaper.width(20)),
                child: GestureDetector(
                    onTap: () {
                      // print(this._rightCateList[index].taobao_cat_id);
                      Navigator.of(context)
                          .push<String>(MaterialPageRoute(builder: (context) {
                        return new TBListPage(
                            search: this._rightCateList[index].name);
                      }));
                    },
                    child: Column(
                      children: <Widget>[
                        ClipOval(
                            child: this._rightCateList[index].icon == null ||
                                    this._rightCateList[index].icon == ''
                                ? Image.asset(
                                    'images/pic_default.png',
                                    width:
                                        ScreenUtil.getInstance().setWidth(80),
                                    height:
                                        ScreenUtil.getInstance().setWidth(80),
                                    fit: BoxFit.cover,
                                  )
                                : CachedNetworkImage(
                                    width:
                                        ScreenUtil.getInstance().setWidth(80),
                                    height:
                                        ScreenUtil.getInstance().setWidth(80),
                                    fit: BoxFit.fill,
                                    imageUrl: Api.BaseUrl +
                                        this._rightCateList[index].icon,
                                    placeholder: (context, url) => Image.asset(
                                      'images/pic_default.png',
                                      width:
                                          ScreenUtil.getInstance().setWidth(80),
                                      height:
                                          ScreenUtil.getInstance().setWidth(80),
                                      fit: BoxFit.cover,
                                    ),
                                    errorWidget: (context, url, error) =>
                                        Image.asset(
                                      'images/pic_default.png',
                                      width:
                                          ScreenUtil.getInstance().setWidth(80),
                                      height:
                                          ScreenUtil.getInstance().setWidth(80),
                                      fit: BoxFit.cover,
                                    ),
                                  )
                            //  Image.network(
                            //     Api.BaseUrl+this._rightCateList[index].icon,
                            //     fit: BoxFit.cover),
                            ),
                        Container(
                          height: ScreenUtil.getInstance().setHeight(40),
                          child: Text(
                            "${this._rightCateList[index].name}",
                            maxLines: 1,
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE)),
                          ),
                        )
                      ],
                    )),
              );
            },
          ),
        ),
      );
    } else {
      return Expanded(
          flex: 1,
          child: Container(
            padding: EdgeInsets.all(10),
            height: double.infinity,
            color: Color.fromRGBO(240, 246, 246, 0.9),
            child: Text('加载中...'),
          ));
    }
  }

  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // super.build(context); //必须添加
    //计算右侧GridView宽高比：
    var leftWidth = ScreenUtil.getInstance().setWidth(750)/ 4;
    //右侧宽高=总宽度-左侧宽度-Gridview外层元素左右的Padding值-GridView中间的间距
    var rightItemWidth = (ScreenUtil.getInstance().setWidth(750) - leftWidth - 20 - 20) / 3;
    rightItemWidth = ScreenUtil.getInstance().setWidth(rightItemWidth);
    var rightItemHeigth =
        rightItemWidth + ScreenUtil.getInstance().setHeight(32);

    return Scaffold(
        appBar: AppBar(
          title: _buildSearch(),
        ),
        body: Container(
            child: 
            // new EasyRefresh(
            //     //刷新  加载组件
            //     enableControlFinishRefresh: true,
            //     enableControlFinishLoad: true,
            //     controller: _controller,
            //     header: MaterialHeader(),
            //     footer: MaterialFooter(),
            //     child:_leftCateList.length > 0? 
                Row(
                  children: <Widget>[
                    _leftCateWidget(leftWidth),
                     _rightCateWidget(rightItemWidth, rightItemHeigth)
                   
                  ],
                )
                // :Text('加载中')
                // )
                ));
  }

   //搜索组件
  _buildSearch() {
    return new Container(
      child: Row(
        children: <Widget>[
          Container(
            // color: Colors.red,
            width: ScreenUtil.getInstance().setWidth(500),
            child: new MaterialButton(
              height: ScreenUtil.getInstance().setWidth(60),
              child: Row(
                children: <Widget>[
                  new Icon(Icons.search, color: Colors.grey),
                  new Text('搜索'),
                ],
              ),
              onPressed: () {
                 Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (context) {
                              return new SearchGoodsPage(type:'1');
                            }));
              },
              color: Colors.white,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20)),
            ),
          ),
        ],
      ),
      width: double.maxFinite,
      margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
    );
  }
}
